#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
from core import main
from conf import setting
import os
import configparser
import paramiko
import threading
class Cmd_operate(object):
    def __init__(self):
        pass
    def menu(self):
        choise_menu = '''
                \033[1;31m
                ---------Use Cmd----------
                1. 选择主机执行
                2. 选择主机组批量执行
                3. 返回上一级目录
                4. 退出
                \033[0m
                '''
        menu_dict = {
            '1':Cmd_operate.use_host,
            '2':Cmd_operate.use_host_group,
            '3':Cmd_operate.go_back,
            '4':'exit'
        }
        while True:
            print(choise_menu)
            choise = input('请选择>>>')
            if choise in menu_dict:
                if choise == '4':
                    exit()
                else:
                    menu_dict[choise](self)
            else:
                print('输入错误！')

    def use_host(self):
        host_path = setting.HOST_FILE_PATH
        group_list = os.listdir(host_path)
        for index, item in enumerate(group_list):
            print(index, item)
        group_choise = input('请选择主机组>>>')
        if group_choise.isdigit():
            if group_list[int(group_choise)]:
                save_path = os.path.join(setting.HOST_FILE_PATH, group_list[int(group_choise)])
                config = configparser.ConfigParser()
                config.read(save_path) #读取选取的主机组
                host_list = config.sections()
                for index, item in enumerate(host_list):
                    print(index, item)
                host_choise = input('请选择需要操作的主机>>>')
                if host_choise.isdigit():
                    if host_list[int(host_choise)]:
                        host_info = {} #将需求的主机放入列表
                        use_host = host_list[int(host_choise)]
                        host_info['hostname'] = config.get(use_host,'hostname')
                        host_info['port'] = config.getint(use_host,'port')
                        host_info['user'] = config.get(use_host,'user')
                        host_info['passwd'] = config.get(use_host,'passwd')
                        print(host_info)
                        cmd=input('>>>')
                        cmd_obj=Cmd_operate()
                        cmd_obj.paramiko_cmd(host_info,cmd) #将主机信息和需要执行的操作传给paramiko模块进行操作
                        #print(hostname,port,user,passwd)


    def use_host_group(self):
        host_path = setting.HOST_FILE_PATH
        group_list = os.listdir(host_path)
        for index, item in enumerate(group_list):
            print(index, item)
        group_choise = input('请选择主机组>>>')
        if group_choise.isdigit():
            if group_list[int(group_choise)]:
                save_path = os.path.join(setting.HOST_FILE_PATH, group_list[int(group_choise)])
                config = configparser.ConfigParser()
                config.read(save_path)
                host_list = config.sections()#获取主机组中所有主机
                t_obj=[] #创建一个空列表用来存放线程
                cmd_obj = Cmd_operate()
                cmd = input('>>>')
                for i in host_list:
                    host_info = {}
                    host_info['hostname'] = config.get(i, 'hostname')
                    host_info['port'] = config.getint(i, 'port')
                    host_info['user'] = config.get(i, 'user')
                    host_info['passwd'] = config.get(i, 'passwd')
                    t =threading.Thread(target=cmd_obj.paramiko_cmd,args=(host_info,cmd))#创建一个线程执行paramiko模块
                    t.start() #启动线程
                    t_obj.append(t) #为了不阻塞后面的线程启动，添加进之前的空列表
                for f in t_obj:#循环线程实例列表，等待所有线程执行完毕
                    f.join() #等待线程执行完毕


    def go_back(self):
        back_obj = main.Manage()
        back_obj.user_choise()

    def paramiko_cmd(self,host_info,cmd):
        # 创建SSH对象
        ssh = paramiko.SSHClient()
        # 允许连接不在know_hosts文件中的主机
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # 连接服务器
        try:
            ssh.connect(hostname=host_info['hostname'], port=host_info['port'], username=host_info['user'], password=host_info['passwd'])
            # 执行命令
            stdin, stdout, stderr = ssh.exec_command(cmd)
            # 获取命令结果
            # result = stdout.read()
            res,err = stdout.read(),stderr.read()
            result = res if res else err
            print('\n==============%s=================' %host_info['hostname'])
            print(result.decode())

            # 关闭连接
            #ssh.close()
        except TimeoutError  as e:
            print(e)

